package com.kvn.backdoor.web;

import com.kvn.backdoor.common.BackdoorException;
import com.kvn.backdoor.common.OpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalHandler {

    static final Logger log = LoggerFactory.getLogger(GlobalHandler.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public OpResponse defaultErrorHandler(HttpServletRequest req, Exception e) {
        log.error("GlobalHandler log", e);
        return OpResponse.fail(500, ExceptionInterpreter.getExceptionInterpreter(e.getClass()).translateExceptionMsg(e));
    }

    @ExceptionHandler(value = BackdoorException.class)
    @ResponseBody
    public OpResponse applicationExceptionHandler(HttpServletRequest req, BackdoorException e) {
        log.error("GlobalHandler log", e);

        return OpResponse.fail(e.getCode(), e.getMessage());
    }

}
